const fs = require('fs')
const tunnel = require('tunnel')
const { translate } = require('@vitalets/google-translate-api')

const flattenObject = (obj, prefix = '') => {
  let result = {}
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      const nestedKey = prefix.length > 0 ? `${prefix}/${key}` : key
      if (typeof obj[key] === 'object' && obj[key] !== null) {
        const nestedObj = flattenObject(obj[key], nestedKey)
        result = { ...result, ...nestedObj }
      } else {
        result[nestedKey] = obj[key]
      }
    }
  }
  return result
}

const unflattenObject = (obj) => {
  const result = {}
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      const nestedKeys = key.split('/')
      let nestedObj = result
      for (let i = 0; i < nestedKeys.length; i++) {
        const nestedKey = nestedKeys[i]
        if (!Object.prototype.hasOwnProperty.call(nestedObj, nestedKey)) {
          nestedObj[nestedKey] = {}
        }
        if (i === nestedKeys.length - 1) {
          nestedObj[nestedKey] = obj[key]
        }
        nestedObj = nestedObj[nestedKey]
      }
    }
  }
  return result
}

const googleTranslator = (text) => translate(
  text,
  { from: 'en', to: 'zh-CN' },
  {
    agent: tunnel.httpsOverHttp({
      proxy: {
        host: 'localhost',// 代理 ip
        port: 15236, // 代理 port
        headers: {
          'User-Agent': 'Node'
        }
      }
    })
  }
)
// 读取 json 文案文件
const sourceJson = require('./en.json')
// 定义翻译方法
const translateRun = async (inputJson) => {
  inputJson = flattenObject(inputJson)
  let chunkValuesLength = 0
  let chunk = []
  const chunks = []
  const sourceKeyValues = Object.entries(inputJson)
  sourceKeyValues.forEach(([key, value]) => {
    // Google 翻译单次最大字符长度 5000 字, 5 为占位分隔符长度
    if (chunkValuesLength + value.length + 5 >= 5000) {
      chunks.push(chunk)
      chunkValuesLength = 0
      chunk = []
    } else {
      chunk.push({ key, value })
      chunkValuesLength += (value.length + 5)
    }
  })
  if (chunk.length > 0) {// 遍历完后检查不满 5000 字符的遗留
    chunks.push(chunk)
    chunkValuesLength = 0
    chunk = []
  }
  const resultJson = {}
  for (let i = 0; i < chunks.length; i++) {
    const chunk = chunks[i]
    const mergeText = chunk.map(v => v.value).join('\n###\n')// 合并文案
    const { text } = await googleTranslator(mergeText)
    const resultValues = text.split(/\n *# *# *# *\n/).map((v) => v.trim())// 拆分文案
    if (chunk.length !== resultValues.length) {
      throw new Error('翻译前文案碎片长度和翻译后的不一致')
    }
    chunk.forEach(({ key }, index) => {
      resultJson[key] = resultValues[index]
    })
  }
  return unflattenObject(resultJson)
}
// 将翻译结果写入硬盘
translateRun(sourceJson).then(resultJson => {
  fs.writeFileSync('./zh.json', JSON.stringify(resultJson))
})